<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/9 0009
 * Time: 09:45
 */

namespace app\api\controller;


use app\admin\model\Logistical;
use app\admin\model\LogisticalRrule;
use app\admin\model\Logistics;
use app\admin\model\Productspecgroups;
use app\admin\model\Tenantdistributionlinkstore;
use app\admin\model\Tenantdistributiontype;
use app\common\model\BaseModel;
use app\common\model\Orderproductdetail;
use app\common\model\Store;
use gaodeapi\gaoDeApi;
use kuaidiniao\KuaiDiniaoApi;

class Tenant extends BaseController
{
    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 配送规则
     */
    public function getTenantDistribution()
    {
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能这空');
        } else if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId不能这空');
        } else {
            $tenantId = $param->tenantId;
            $storeId = $param->storeId;
            $distributionType = Tenantdistributiontype::where(['tenantId' => $tenantId, 'status' => 1])->select();
            if (empty($distributionType)) {
                return show(config('status.EMPTY_STATUS'), self::NOT_DATA, '未查到配送规则');
            } else {
                $data = null;
                foreach ($distributionType as $type) {
                    // 到店自提
                    if ($type->distributionType == 1) {

                        if($type->applicableType == 2) {
                            $find = Tenantdistributionlinkstore::where(['tenantDistributionId' => $type->id,'storeId' => $storeId,'status'=>1])->find();
                            if($find) {
                                $data['pickedUp'] = $type;
                            }
                        } else if($type->applicableType == 1) {  //适用所有门店
                            $data['pickedUp'] = $type;
                        }
                        
                    }
                    // 物流配送
                    if ($type->distributionType == 2) {
                        if($type->deliverMethod == 1){
                            //商家自行配送
                            $logistics = Logistics::where('tenantId', $tenantId)->find();
                            $logistics->deliverMethod = 1;
                            $data['logistics'] = $logistics;
                        }elseif ($type->deliverMethod == 0){
                            //快递物流
                            $logistical = Logistical::where(['tenantId'=>$tenantId,'tenantDistributionId'=>$type->id])->find();
                            $logistical->deliverMethod = 0;
                            $LogisticalRrule = LogisticalRrule::where('logistical_id',$logistical->id)->find();
                            $logistical->LogisticalRrule = $LogisticalRrule;
                            $data['logistics'] = $logistical;
                        }else{
                            //TODO
                            $logistics = (object)array();
                            $logistics->deliverMethod = 2;
                            $data['logistics'] = $logistics;
                        }

                    }

                }
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
            }
        }
    }





    /**
     * @param $param
     * @return array|false|\PDOStatement|string|\think\Model
     * 获取商户配送信息
     */
    public function getlogistics($param){
       $loginsticsModel = new Logistics();
      return $loginsticsModel->getlogistics($param);
    }

    /**
     * @param $distributiontypeId
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 查询物流费用配置
     */
    private function findLogistical($distributiontypeId){
        $logisticalModel = new Logistical();
        return $logisticalModel->findTypeLogistical($distributiontypeId);
    }


    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取商户开启物流类型
     */
    public function getTenantDistributionType(){
        $param = self::getHttpParam();
        if (empty($param->tenantId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'tenantId不能这空');
        } else if (empty($param->storeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'storeId不能这空');
        } else {
            $tenantId = $param->tenantId;
            $storeId = $param->storeId;
            $typeModel = new Tenantdistributiontype();
            $TdTypes = $typeModel->getTentanTypes($tenantId);
            $resArray = array();
            $linkStore1 = array();
            $logistics = array();
            $param = array();
            foreach ($TdTypes as $item){
               $id = $item->id;
               $tenantdistribution =  $item->tenantdistribution;
               //自取
               if($item->distributionType == $typeModel::Type_1){
                   $tenantDisStoreModel = new Tenantdistributionlinkstore();
                   //适用类型  0物流 1所有门店  2指定门店  //3到店自取
                   //是否开启自取
                   if($item->status == $typeModel::STATUS_1){
                       $param = array(
                           'tenantDistributionId'=>$id,
                           'tenantdistribution'=>$tenantdistribution,
                           'deliverMethod'=>$typeModel::DELIVERMETHOD_3,
                           "packingCharge"=>$item->packingCharge,
                           'is_dis'=>$tenantDisStoreModel::is_dis_1,
                           "deliverMethodName"=>"到店自取",
                       );
                   }
                   $resArray['linkStore'] = $param;
                   }
                   if($item->distributionType == $typeModel::Type_2){
                        $logisticsModel = new Logistics();
                       $fee = self::getTenantDistributionFee($id);

                       //是否开启商家配送
                       if($item->status == $typeModel::STATUS_1){
                           $deliverMethod = $item->deliverMethod;
                           $paramDate['tenantDistributionId'] = $id;

                           $paramDate['deliverMethod'] = $deliverMethod;
                           if($deliverMethod == $typeModel::DELIVERMETHOD_1){
                               //获取当前商品的商家配送
                               $logistics = $this->getlogistics($paramDate);
                               //获取商家配送规则根据规则计算运费

                               $param = array(
                                   'tenantDistributionId'=>$id,
                                   'tenantdistribution'=>$tenantdistribution,
                                   'deliverMethod'=>$deliverMethod,
                                   'is_dis'=>$logisticsModel::is_dis_1,
                                   "deliverMethodName"=>"商家配送",
                                   'feeDetail'=>$fee
                               );

                           }else if($deliverMethod == $typeModel::DELIVERMETHOD_2){
                                    //达达配送
                               $param = array(
                                   'tenantDistributionId'=>$id,
                                   'tenantdistribution'=>$tenantdistribution,
                                   'deliverMethod'=>$deliverMethod,
                                   'is_dis'=>$logisticsModel::is_dis_1,
                                   "deliverMethodName"=>"达达配送",
                                   'logisticsId'=>false,
                                   "msg"=>"请调用达达运费接口！"
                               );
                           }else if($deliverMethod == $typeModel::DELIVERMETHOD_0){
                               $logistical = self::findLogistical($id);
                               if(isset($logistical->logsticalRrule) && !empty($logistical->logsticalRrule) && !empty($logistical)){
                                   $logistical->logsticalRrule;
                               }else{
                                   return show(config('status.SUCCESS_STATUS'), "商家物流配送费用未设置！", $logistical);
                               }
                               //物流配送
                               $param = array(
                                   'tenantDistributionId'=>$id,
                                   'tenantdistribution'=>$tenantdistribution,
                                   'deliverMethod'=>$item->deliverMethod,
                                   'is_dis'=>$logisticsModel::is_dis_1,
                                   "deliverMethodName"=>"物流配送",
                                   'feeDetail'=>$fee
                               );

                           }else{
                               return show(config('status.ERROR_STATUS'), "当前商户物流配送方式不正确！", array());
                           }
                           $resArray['logisticsDate'] = $param;
                       }else{
                           return show(config('status.ERROR_STATUS'), "当前商户物流配送状态未开启！", array());
                       }
                   }
               }
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $resArray);
        }
    }

    /**
     * @param $productIds
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 根据商品id组合获取商品信息集合
     */
    private function getProductList($productIds){
       $productModel = new \app\common\model\Product();
       $productResult = $productModel->getProductList($productIds);
        return $productResult;
    }

    /**
     * @param $productSpecId
     * @return array|false|\PDOStatement|string|\think\Model
     * 查询多规格商品信息
     */
    private function getProductSpec($productSpecId){
        $productSpecGroupsModel = new Productspecgroups();
        $productSpec = $productSpecGroupsModel->getProductSpec($productSpecId);
        return $productSpec;
    }

    /**
     * @param $productParam
     * @param $productId
     * @return mixed
     * 获取多商品规格id以及购买数量
     */
    private function getProductSpecId($productParam,$productId){
        foreach ($productParam as $item){
            if($productId == $item['productId']){
                $data['specId'] = $item['specId'];
                $data['count'] = $item['productCount'];
            }
        }
        return $data;
    }

    /**
     * @param $param
     * @param $productParams
     * @return array
     * 获取用户购买商品数量
     */
    private function getProductData($productParam,$productId){
        foreach ($productParam as $item){
        if($item['productId'] == $productId){
            return $item['productCount'];
            }
        }
    }

    /**
     * @param $param
     * @param $productParams
     * @return array
     * 获取用户购买商品重量和商品价格和数量
     */
    private function getProductParam($param,$productParams){
        $specClass = $param['specClass'];
        $productModel = new \app\common\model\Product();
        $data['productId'] = $param['id'];
        $baseModel = new BaseModel();

        //单规格获取重量
        if($specClass == $productModel::SPEC_CLASS_1){
            //$weight = $param['weight'];
            $productCount = self::getProductData($productParams,$param['id']);
            $data['count'] = $productCount;
            $data['currentPrice'] = $param['currentPrice'];
            $data['weight'] = $param['weight'];
            $data['code'] = $baseModel::STATUS_VALID;
            return $data;
        }

        //多规格获取重量
        if($specClass == $productModel::SPEC_CLASS_2){
            //根据多规格Id获取商品对应多规格价格及重量
            $specParam = self::getProductSpecId($productParams,$param['id']);
            $productSpec = self::getProductSpec($specParam['specId']);
            $data['count'] = $specParam['count'];
            $data['currentPrice'] = $productSpec['currentPrice'];
            $data['weight'] = $productSpec['weight'];
            $data['code'] = $baseModel::STATUS_VALID;
            return $data;
        }

        return array(
            "code"=>$baseModel::STATUS_INVALID
        );
    }

    /**
     * @param $param
     * @return bool|string
     * 拼接商品id
     * productid拼接字符串
     */
    private function getProductIds($param){
        $productIds = "";
        foreach ($param as $item){
            $productIds .=$item['productId'].",";
        }

        $productIds = substr($productIds,0,strlen($productIds)-1);
        return $productIds;
    }
    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 通过商品参数获取商品价格数组
     */
    private function getLogisticsFee(){
        $productIds = input("post.productParams");
        $productParams = json_decode($productIds,true);
        $productIds = self::getProductIds($productParams);
        //获取商品信息 计算出运费
        $getProductList = self::getProductList($productIds);
        $productFeeData = array();
        if($getProductList && !empty($getProductList)){
            foreach ($getProductList as $item){
                //获取商品信息获取当前商品id
                $productParam = self::getProductParam($item,$productParams);
                if($productParam['code'] == BaseModel::STATUS_VALID){
                    $productFeeData['code'] = BaseModel::STATUS_VALID;
                    $productFeeData[] = $productParam;
                }else{
                    return array("code"=>BaseModel::STATUS_INVALID);
                }
            }
            return $productFeeData;
        }else{
            return array("code"=>BaseModel::STATUS_INVALID);
        }
    }

    /**
     * @param $param
     * @return array
     * 获取数组参数key
     */
    private function getParamKeys($param){
        $arr = [];
        foreach ($param as $key=>$value){
            $arr[] = $key;
        }
        return $arr;
    }



    //获取距离加价
    private function getDistanceIncreaseFee($distanceIncrease,$distance){
        $distance = $distance/1000;

        $paramKeys = self::getParamKeys($distanceIncrease);
        //距离1-3km
        $distanceIncrease_index_0 = $paramKeys[0];
        $distanceIncrease_index_0 = trim(strrchr($distanceIncrease_index_0, 'distanceIncrease_'),'distanceIncrease_');
        $distanceIncrease_0Array = explode('_',$distanceIncrease_index_0);

        //距离3-5km
        $distanceIncrease_index_2 = $paramKeys[2];
        $distanceIncrease_2 = trim(strrchr($distanceIncrease_index_2, 'distanceIncrease_'),'distanceIncrease_');
        $distanceIncrease_2Array = explode('_',$distanceIncrease_2);

        //根据距离获取距离加价
      if ($distanceIncrease_0Array[0]<$distance && $distance <=$distanceIncrease_0Array[1]){
          $distance = $distanceIncrease_0Array[1]-$distanceIncrease_0Array[0];
          $fee = $distance*$distanceIncrease['distanceIncrease_1_3_val'];
          return $fee;
        }elseif ( $distance>$distanceIncrease_2Array[0] && $distance<=$distanceIncrease_2Array[1]){
          $distanceIncrease_1_3 = $distanceIncrease_0Array[1]-$distanceIncrease_0Array[0];
          $fee_1_3 = $distanceIncrease_1_3*$distanceIncrease['distanceIncrease_1_3_val'];
          $distance = $distanceIncrease_2Array[1]-$distanceIncrease_2Array[0];
          $fee = $distance*$distanceIncrease['distanceIncrease_3_5_val'];
          return $fee+$fee_1_3;
        }else{
          if($distance< 1 ){
              return 0;
          }
          $distanceIncrease_1_3 = $distanceIncrease_0Array[1]-$distanceIncrease_0Array[0];
          $fee_1_3 = $distanceIncrease_1_3*$distanceIncrease['distanceIncrease_1_3_val'];
          $distanceIncrease_3_5 = $distanceIncrease_2Array[1]-$distanceIncrease_2Array[0];
          $fee_3_5 = $distanceIncrease_3_5*$distanceIncrease['distanceIncrease_3_5_val'];
          return $fee_1_3+$fee_3_5;
        }
    }


    //获取重量加价
    private function getWeightIncreaseFee($weightIncrease,$weight){
        $productWeightIncrease = $weight/1000;
        $paramKeys = self::getParamKeys($weightIncrease);
        $weightIncrease_1 = $paramKeys[0];
        $weightIncrease_1_5 = $paramKeys[2];
        $weightIncrease_5_10 = $paramKeys[4];
        $weightIncrease_1 = $weightIncrease[$weightIncrease_1];
        $weightIncrease_1_5 = $weightIncrease[$weightIncrease_1_5];
        $weightIncrease_5_10 = $weightIncrease[$weightIncrease_5_10];
        $weightIncrease_1_5Array = explode('_',$weightIncrease_1_5);
        $weightIncrease_5_10Array = explode('_',$weightIncrease_5_10);
        $weightIncrease_1_val = $weightIncrease['weightIncrease_1_val'];
        $weightIncrease_1_5_val = $weightIncrease['weightIncrease_1_5_val'];
        $weightIncrease_5_10_val = $weightIncrease['weightIncrease_5_10_val'];
        //小于等于1kg价格
        if($productWeightIncrease<=$weightIncrease_1){
            return $weightIncrease_1_val;
        }
        //1-5kg价格
        if($weightIncrease_1_5Array[0] < $productWeightIncrease && $productWeightIncrease<=$weightIncrease_1_5Array[1]){
            $weight = ($weightIncrease_1_5Array[1]-$weightIncrease_1);
            $fee = $weight*$weightIncrease_1_5_val;
            return $fee;
        }
        //5-10kg价格
        if($weightIncrease_5_10Array[0] < $productWeightIncrease && $productWeightIncrease<= $weightIncrease_5_10Array[1] || $productWeightIncrease > $weightIncrease_5_10Array[1] ){
            $weight = ($weightIncrease_1_5Array[1]-$weightIncrease_1);
            $fee_1_5 = $weight*$weightIncrease_1_5_val;
            $weight = $weightIncrease_5_10Array[1]-$weightIncrease_5_10Array[0];
            $fee_5_10 = $weight*$weightIncrease_5_10_val;
            $fee = $fee_5_10+$fee_1_5;
            return $fee;
        }

        if($productWeightIncrease<=0){
            return 0;
        }
    }

    //获取时间加价
    private function getNocturnalPriceIncrease($nocturnalPriceIncrease){

        $dateH = date('H',time());
        $nocturnalPriceIncrease_22_08 = $nocturnalPriceIncrease['nocturnalPriceIncrease_22_08'];
        $nocturnalPriceIncrease_22_08Array = explode('_',$nocturnalPriceIncrease_22_08);
        if( $dateH > $nocturnalPriceIncrease_22_08Array[0] || $dateH<$nocturnalPriceIncrease_22_08Array[1]){
            return $nocturnalPriceIncrease['nocturnalPriceIncrease_22_08_val'];
        }else{
            return 0;
        }
    }

    /**
     * @param $item
     * @param $logistics
     *获取重量加价和距离加价
     */
    private function getWeightFee($logistics,$distance,$weight){

        if($logistics && !empty($logistics)){
            //运费
            $freight = $logistics->freight;
            //距离加价
            $distanceIncrease = $logistics->distanceIncrease;
            $distanceIncrease = json_decode($distanceIncrease,true);
            //时间加价
            $nocturnalPriceIncrease = $logistics->nocturnalPriceIncrease;
            $nocturnalPriceIncrease = json_decode($nocturnalPriceIncrease,true);
            //重量加价
            $weightIncrease = $logistics->weightIncrease;
            $weightIncrease = json_decode($weightIncrease,true);
            //获取距离加价
            $getDistanceIncreaseFee = self::getDistanceIncreaseFee($distanceIncrease,$distance);
            //获取重量加价
            $getWeightIncreaseFee = self::getWeightIncreaseFee($weightIncrease,$weight);
            //获取时间加价
            $getNocturnalPriceIncrease = self::getNocturnalPriceIncrease($nocturnalPriceIncrease);

            $freight = $freight+$getDistanceIncreaseFee+$getWeightIncreaseFee+$getNocturnalPriceIncrease;

            return $freight;
        }
    }

    /**
     * @param $param
     * @return array
     * 商家配送方式运费获取
     */
    private function findLogistics($param){
        $distance = self::getDistance();


        if($distance['status'] == Logistical::STATUS_INVALID){
            return $distance;
        }
        $distance = $distance['district'];
        $logisticsModel = new Logistics();
        $logistics = $logisticsModel->getlogistics($param);

        $logisticsFee = $param['logisticsFee'];
        //  $weight = $logisticsFee['weight'];

        $data = array();
        $param = array();
        if($logisticsFee['code']==BaseModel::STATUS_VALID){
            unset($logisticsFee['code']);
            foreach ($logisticsFee as $item){
                $data[] = $item['weight']*$item['count'];
            }
            $weight = $data[0]+$data[1];
            $freight = self::getWeightFee($logistics,$distance,$weight);
            $param['freight'] = $freight;
            $param['deliverMethod'] =$logistics->deliverMethod;
            $param['orderStartingPrice'] = $logistics->orderStartingPrice;
            $param['packingCharge'] = $logistics->packingCharge;
        }
        $param['status'] = Logistical::STATUS_VALID;
        $param['freight'] = $freight;
        $param['deliverMethod'] =$logistics->deliverMethod;
        $param['orderStartingPrice'] = $logistics->orderStartingPrice;
        $param['packingCharge'] = $logistics->packingCharge;


        return $param;
    }


    /**
     * @param $userAddress
     * @return array
     * 获取收货人高德地图经纬度
     */
    public function getUserLanLng($userAddress){

        $gaodeApi = new gaoDeApi();
        $param['address'] = $userAddress;
        $getAdders = $gaodeApi->getAddres($param);
        $getAdders = json_decode($getAdders);
        $geocodes = explode(',',$getAdders->geocodes[0]->location);
        return $geocodes;
    }

    /**
     * @return mixed
     * 获取店铺地址到收货人地址之间距离
     */
    private function getDistance(){
        $storeId = input("storeId");//店铺id
        $userAddress = input("userAddress");//用户收货地址
        if(!$storeId){
            return ['status'=>Logistics::STATUS_INVALID,'message'=>"storeId不能为空！"];
        }
        if(!$userAddress){
            return ['status'=>Logistics::STATUS_INVALID,'message'=>"用户地址不能为空！"];
        }

        $storeModel = new Store();
        $store = $storeModel->findStore($storeId);

        if($store && !empty($store)){
            $city = $store->city;
            $district = $store->district;
            $province = $store->province;
            $address = $store->address;
            $storeAddress = $province.$city.$district.$address;
            $gaodeapi = new gaoDeApi();
            $param['address'] = $storeAddress;
            $getAdders = $gaodeapi->getAddres($param);
            $res = json_decode($getAdders);
            $geocodes = explode(',',$res->geocodes[0]->location);
      /*      $longitude = $geocodes[0];      //店铺地址经度
            $latitude = $geocodes[1];       //店铺地址纬度*/
        }

        $StoreGeocodes = implode(',',$geocodes);
        $userGeocodes = self::getUserLanLng($userAddress);
/*      $userLongitude = $userGeocodes[0];      //收货人地址经度
        $userLatitude = $userGeocodes[1];       //收货人地址纬度*/

        $userGeocodes = implode(',',$userGeocodes);

        $district = $gaodeapi->bicycling($StoreGeocodes,$userGeocodes);

        return $district;
    }


    /**
     * @param $logistical
     * @param $count
     * @return float|int
     * 根据数量计算物流费用
     */
    private function getfreight($logistical,$count){
        $logsticalRrule = isset($logistical->logsticalRrule)?$logistical->logsticalRrule:"";
        $first_money = 0;
        $continued_money = 0;
        if($logsticalRrule->first_num < $count){
            $first_money = $logsticalRrule->first_money;
        }
        $continued_num = $count-$logsticalRrule->first_num;
        if($logsticalRrule->continued_num){
            $continued_money = $continued_num/$logsticalRrule->continued_num*$logsticalRrule->continued_money;
        }
        $money = $first_money+$continued_money;
        return $money;
    }


    /**
     * 根据重量计算物流费用
     */
    private function getWeightFreight($logistical,$weight){
        $logsticalRrule = isset($logistical->logsticalRrule)?$logistical->logsticalRrule:"";
        if(!$logsticalRrule){
            return false;
        }
        $weight = $weight/1000;   //单位kg

        $first_money = 0;
        $continued_money = 0;
        $first_num = $logsticalRrule->first_num;
        $continued_num = $logsticalRrule->continued_num;
        $first_money = $logsticalRrule->first_money;
        $continued_money = $logsticalRrule->continued_money;
        $weight = $weight-$first_num;

        $freight = $weight/$continued_num*$continued_money;

        return $freight;
    }

    //根据物流运费类型获取物流
    private function getLogisticalFreight($logistical,$count,$weight){
        $freight_type = $logistical->freight_type;
        if($freight_type == Logistical::FREIGHT_TYPE_0){
            //物流统一运费
            return $logistical->logsticalRrule->first_money;
        }

        if($freight_type == Logistical::FREIGHT_TYPE_1){
            //物流按件数计算运费
        $freight =  self::getfreight($logistical,$count);
        return $freight;
        }

        if($freight_type == Logistical::FREIGHT_TYPE_2){
            //物流按重量计算运费
          $fee =  self::getWeightFreight($logistical,$weight);
            return $fee;
        }

    }

    /**
     * @param $feeParam
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 根据配送方式获取配送费用
     */
    private function getFee($feeParam){

       // $storeLntLag = input("userLatlng");//用户经纬度字符串
        //根据商户配送方式获取对应配送规则
       if($feeParam['deliverMethod'] == Tenantdistributiontype::DELIVERMETHOD_0){

           //商户物流配送规则
           $tenantDistributionId = $feeParam['tenantDistributionId'];

           $logistical = self::findLogistical($tenantDistributionId);

           $logisticsFee = $feeParam['logisticsFee'];

           $arr = null;
           $count =0 ;
           $weightArr = array();
           $weight = 0;

           if($logisticsFee['code'] == Logistical::STATUS_VALID){
               unset($logisticsFee['code']);

               foreach ($logisticsFee as $item){
                   $arr[] = $item['count'];
                   $weightArr[] = $item['weight'];
               }
               foreach ($arr as $item){
                   $count += $item;
               }

               foreach ($weightArr as $item){
                   $weight += $item;
               }

                $data['count'] = $count;
                $data['weight'] = $weight;

           }

           $packingCharge = $logistical->packingCharge;//打包费用
           $freight_type = $logistical->freight_type;//运费类型

           //根据运费类型获取对应运费价格
           $logisticalFeeData = self::getLogisticalFreight($logistical,$data['count'],$data['weight']);
           $param['packingCharge'] = $packingCharge;
           $param['freight'] = $logisticalFeeData;
           $param['status'] = Logistical::STATUS_VALID;
            return $param;

       }elseif ($feeParam['deliverMethod'] == Tenantdistributiontype::DELIVERMETHOD_1){

           //商户自行配送规则
           $data = self::findLogistics($feeParam);

           return $data;

       }elseif ($feeParam['deliverMethod'] == Tenantdistributiontype::DELIVERMETHOD_2){



       }else{



       }

    }

    /**
     * @return \think\response\Json
     * 获取商家配送价格
     */
    public function getTenantDistributionFee($id){
        //$logisticsId = input('post.logisticsId');                   //物流id
        //$deliverMethod = input('post.deliverMethod');               //配送方式
        $tenantDistributionId = $id; //商户配送方式类型id
        $tenantdistributiontypeModel = new Tenantdistributiontype();
        if(!$tenantDistributionId){
            $param = array();
            $param['status'] == Logistical::STATUS_INVALID;
            $param['message'] == "商户id不能为空！";
            return  $param;
        }

        //获取商户配送类型
        $findTenantdistributiontype = $tenantdistributiontypeModel->findTdtType($tenantDistributionId);

        if($findTenantdistributiontype && $findTenantdistributiontype->status!=$tenantdistributiontypeModel::STATUS_INVALID){

            //根据商户配送方式获取对应的价格；
            $feeParam['deliverMethod'] = $findTenantdistributiontype->deliverMethod;

            $feeParam['tenantDistributionId'] = $findTenantdistributiontype->id;

            //根据配送方式获取对应的配送规则计算出运费

            $logisticsFee = $this->getLogisticsFee();

            $feeParam['logisticsFee'] = $logisticsFee;

            $data = self::getFee($feeParam);

            if($data['status'] == Logistical::STATUS_VALID){

                return $data;

            }else{

                return $data;

            }
        }else{
            $param = array();
            $param['status'] == Logistical::STATUS_INVALID;
            $param['message'] == "商户物流配送状态未开启！";
            return  $param;
        }
    }

    /**
     *
     */
    private function getUserAddress($userAddress){

/*        $userProvinceFirst = substr($userAddress,0,strpos($userAddress, '省'));

        $userAddressCityLast = substr($userAddress,strpos($userAddress,'省')+1);

        $userAddressDistrict = substr($userAddressCity,0,strpos($userAddressCity, '市'));

        $userAddressDistrict = substr($userAddressDistrict,strpos($userAddressDistrict,'市')+1);

        $userAddressDistrict = substr($userAddressDistrict,strpos($userAddressDistrict,'区')+1);

        $userAddressDistrict = substr($userAddressDistrict,strpos($userAddressDistrict,'区')+1);*/


        $userProvince = substr($userAddress,0,strpos($userAddress, '省'));
        $userProvince = substr($userAddress,0,strpos($userAddress, '省'));
        $userProvince = substr($userAddress,0,strpos($userAddress, '省'));

    }

    /**
     * @return mixed
     */
    public function getLogisticalPush()
    {
        $kuaidiniaoapi = new KuaiDiniaoApi();
        $logistics = new \app\admin\controller\Logistics();
        $orderId  = input("post.orderId");
        $orderModel = new \app\common\model\Order();
        $order = $orderModel->getCurrentOrder($orderId);

        $userName = $order->userName;
        $userPhone = $order->userPhone;
        $deliverAddress = $order->deliverAddress;




        $storeId = $order->storeId;
        $store = Store::getCurrentOrder($storeId);

        $storeProvince = $store->province;
        $storeCity = $store->city;
        $storeDistrict = $store->district;
        $storeAddress = $store->address;


        $logisticsCode = $logistics->LogisticsCode();

        //$shipperCode = $logisticsCode['ZTO'];

        $RequestData = array();

        $RequestData['ShipperCode'] ='YTO';   //快递公司编号

        $RequestData['LogisticCode'] ="809726387339";  //快递单编号

        $RequestData['Receiver']['Name'] =$userName;          //Name

        $RequestData['Receiver']['Mobile'] = $userPhone;  //手机

        $RequestData['Receiver']['ProvinceName'] =$province;

        $RequestData['Receiver']['CityName'] =$city;

        $RequestData['Receiver']['ExpAreaName'] =$district;

        $RequestData['Receiver']['Address'] =$address;

        $RequestData['Sender']['Name'] =$userName;

        $RequestData['Receiver']['Mobile'] = $store->phone;  //手机
        $RequestData['Sender']['ProvinceName'] =$storeProvince;
        $RequestData['Sender']['CityName'] =$storeCity;
        $RequestData['Sender']['ExpAreaName'] =$storeDistrict;
        $RequestData['Sender']['Address'] =$storeAddress;
        $RequestData['url'] = "http://sandboxapi.kdniao.cc:8080/kdniaosandbox/gateway/exterfaceInvoke.json";



      $kuaidiniaoapi->getOrderTracesByJson();
    }

}